import { useEffect, useState } from 'react'
import ImageGrid, { ImageCardProps } from '../../../component/ImageGrid'
import { useAppDispatch, useAppSelector } from '../../../hooks/store'
import { detailReset, fetchPublicPictures, publicPitcturePagerAdd } from '../../../store/slice/publicPicture'
import useWindowSize from '../../../hooks/size'
import useWindowDistance from '../../../hooks/distance'

const HomeContent = () => {
    const dispatch = useAppDispatch()
    const publicState = useAppSelector((state) => state.publicPicture)
    const [columnCount,setColumnCount] = useState<number|undefined>()
    const { width, height } = useWindowSize()
    const pager = publicState.pager
    useEffect(() => {
        if (publicState.status === 'idle') {
            console.log('get public list')
            
            dispatch(fetchPublicPictures({ page: pager.page, pageSize: pager.pageSize }))
        }
    }, [dispatch, pager.page, pager.pageSize, publicState.status])
    useEffect(()=>{
        console.log(width,height)
        const cc = Math.floor((width - 400) / 300)
        // console.log(cc)
        setColumnCount(cc)
    },[height, width])
    const data: ImageCardProps[] = publicState.list.map((i) => ({ id: i.id, src: i.imageUrl, title: i.title, desc: i.desc }))
    const {scrollTop,scrollDown} = useWindowDistance()
    useEffect(()=>{
        console.log(scrollTop,scrollDown)
        if (scrollDown < 200 && publicState.status === 'succeeded') {
            console.log('enter down')
            dispatch(publicPitcturePagerAdd())
        }
    },[dispatch, publicState.status, scrollDown, scrollTop])
    useEffect(()=>{ 
        return ()=>{
            dispatch(detailReset)
        }
    })
    return (
        <>
            <ImageGrid data={data} type={2} columnCount={columnCount} />
        </>
    )
}

export default HomeContent